package com.cbj.netty.server;
import com.cbj.netty.handler.HttpServerRequestHandler;
import com.cbj.netty.handler.ServerDecoder;
import com.cbj.netty.handler.ServerRequestHandler;
import com.cbj.netty.protocol.Content;
import com.cbj.netty.rpc.Dispatcher;
import com.cbj.netty.util.RPCUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

import java.net.InetSocketAddress;


/**
 * @author Godc
 * @description
 */
public class Server {

    public static void startServer(){
        // 实现简易版的注册中心,将可能要使用的类都注册进去
        MyCat myCat = new MyCat();
        MyDog myDog = new MyDog();
        Dispatcher dispatcher = Dispatcher.getDispatcher();
        dispatcher.register(Cat.class.getName(),myCat);
        dispatcher.register(Dog.class.getName(),myDog);

        NioEventLoopGroup boss = new NioEventLoopGroup(8);
        NioEventLoopGroup worker = boss;
        ChannelFuture localhost = new ServerBootstrap()
                .group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //1.这里是rpc的解码过程
                        ch.pipeline().addLast(new ServerDecoder());
                        ch.pipeline().addLast(new ServerRequestHandler(dispatcher));
                        // 2.这里是基于Http的解码过程,Netty有对应的解码器
//                        ch.pipeline().addLast(new HttpServerCodec());
//                            // 2.1这里是将头体聚合
//                        ch.pipeline().addLast(new HttpObjectAggregator(1024*512));
//                        ch.pipeline().addLast(new HttpServerRequestHandler());
                    }
                }).bind(new InetSocketAddress("localhost", 9090));
        try {
            localhost.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}










